<template>
  <div class="big-box">
    <div class="center">
      <div class="add-button">
        <n-button @click="showModal = true">新增课程</n-button>
      </div>

      <div class="A">
        <el-table @row-dblclick="onRow" :data="pageDate" style="width: 100%;border-radius: 10px;">
          <el-table-column prop="courseCover" label="封面" width="120" #default="one">
            <el-image class="FM_img" :src="one.row.courseCover" />
          </el-table-column>
          <el-table-column prop="courseTitle" label="标题" width="150"></el-table-column>
          <el-table-column label="简介" width="250" #default="Intro">
            <span class="text-container">{{ Intro.row.courseIntro }}</span>
          </el-table-column>
          <el-table-column prop="updateTime" label="最近修改时间" min-width="250"></el-table-column>
          <el-table-column prop="courseIntro" label="编辑课程" width="120" #default="upDate">
              <el-image src="/src/assets/svg/editor.svg" @click="editor(upDate.row.courseId)" class="bj-img" />
          </el-table-column>
          <el-table-column prop="courseIntro" label="删除课程" width="120" #default="upDate">
            
            <el-popconfirm title="确认删除该课程?" @confirm="onDelete(upDate.row.courseId)">
                        <template #reference>
                          <el-image src="/src/assets/svg/delete5.svg" class="bj-img" />
                        </template>
                    </el-popconfirm>
          
          </el-table-column>
        </el-table>
      </div>
      
    </div>
  </div>

  <!-- 弹窗 -->
  <n-modal v-model:show="showModal" :mask-closable="false">
    <n-card style="width: 600px;" title="新增课程" role="dialog" aria-modal="true">
      <!-- 关闭框 -->
      <template #header-extra>
        <img src="/src/assets/svg/delete.svg" class="deleye-img" @click="showModal = false">
      </template>
      <div>
        <div @click="onUploadImg()">
          <el-tooltip effect="light" content="点击选择课程封面" placement="left">
            <img v-if="imageUrl" :src="imageUrl" class="avatar-uploader-icon" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-tooltip>
        </div>

      <div class="xz-bj">
      <span style="min-width: 105px;">课程班级:</span>
      <n-select v-model:value="classIdArray" style="width: 100%" multiple :options="selectOptions" />
    </div>

        标题: <n-input v-model:value="courseTitle" type="text" placeholder="请输入课程名" maxlength="30" show-count clearable />
        简介: <n-input v-model:value="courseIntro" type="textarea" placeholder="请输入课程简介" maxlength="150" show-count
          clearable />
      </div>
      <!-- 提交按钮 -->
      <template #footer>
        <div style="display: flex;justify-content: flex-end;">
          <n-button @click="onSubmit()">提交</n-button>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>

<script setup>
import { onMounted, ref,computed } from 'vue';
import { Plus } from '@element-plus/icons-vue'
import { addCourse } from '@/api/filesHttp';
import { openInfo } from '@/utils/openInfo';
import adminHttp from '@/api/adminHttp';
import { useRouter } from 'vue-router';
import teacherHttp from '@/api/teacherHttp';
import useUserStore from '@/stores/useUserStore';
import { refWithControl } from '@vueuse/core';
const userStore = useUserStore()
const router = useRouter()
const pageDate = ref([])
const showModal = ref(false)
//该老师的班级数据
const classInfo = ref([])
//选中的班级
const classIdArray = ref([])
const courseTitle = ref('')
const courseIntro = ref('')

//页面展示的图片
const imageUrl = ref('')
//图片url
const imgFile = ref()

//课程删除
function onDelete(courseId){
  teacherHttp.deleteCourse(courseId).then((res)=>{
    if (res.code ==200) {
      //重新拉取数据
      getCourseList()
    }
    
  })
}
//班级选项
const selectOptions = computed(() => {
  return classInfo.value.map(item => ({
    label: item.className,
    value: item.classId
  }));
})

/* 图片文件上传事件 */
function onUploadImg() {
  const inputEl = document.createElement("input"); //创建input元素
  inputEl.type = "file"; //数据类型
  inputEl.accept = "image/*"; // 可以设置接受的文件类型，例如'*/*'表示任何类型
  inputEl.multiple = false; // 设置只能选择一个文件
  inputEl.click(); //点击元素
  inputEl.addEventListener("change", function () {
    //用户选中的文件
    imgFile.value = inputEl.files[0];
    // 如果选择了图片 选中文件后展示到页面
    if (imgFile.value) {
      const reader = new FileReader();
      reader.onload = (e) => {
        //转换为baase 64的图片展示到选项框
        imageUrl.value = e.target.result;
      };
      reader.readAsDataURL(imgFile.value);
    }
  })
}

//跳转到章节页面
const editor = (courseId) => {
  router.push({ name: 'CourseEditor', params: { courseId: courseId } })
}

//获取初始化数据
function getCourseList() {
  adminHttp.getCourseList().then((res) => {
    pageDate.value = res.data
    //格式化时间，去除T
    for (let i = 0; i < pageDate.value.length; i++) {
      pageDate.value[i].updateTime = pageDate.value[i].updateTime.replace("T", " ")
      
    }
    console.log("获取初始化课程数据",res);
  })
}

//初始化
onMounted(() => {
  getCourseList()
  getClassList()
})

function onRow(rowdata) {
  console.log(rowdata);
}

//点击提交数据
function onSubmit() {
  if (imageUrl.value == '' || courseIntro.value == "" || classIdArray.value==[]|| courseTitle.value == "") {
    openInfo("表单填写不完整！")
  } else {
    // 创建From对象装图片file
    const filesForm = new FormData();
    filesForm.append("file", imgFile.value);
    filesForm.append("classIdArray",classIdArray.value)
    filesForm.append("createTeacherId",userStore.userInfo.userId)
    filesForm.append("courseTitle", courseTitle.value);
    filesForm.append("courseIntro", courseIntro.value);
    addCourse(filesForm).then((res) => {
      if (res.code == 200) {
        imageUrl.value = ''; courseIntro.value = ''; courseTitle.value = '';classIdArray.value==[];
        //重新拉取数据
        getCourseList()
        openInfo("修改成功", 'success')
      } else {
        openInfo("修改失败", 'error')
      }
    })
  }
  showModal.value = false
}

//获取该老师的班级信息
const getClassList = ()=>{
  teacherHttp.getClassList(userStore.userInfo.userId).then((res)=>{
    if (res.code==200) {
      classInfo.value=res.data
      //console.log("班级",classInfo.value);
    }
  })
}


</script>

<style scoped>
.big-box {
  width: 100%;
  display: flex;
  justify-content: center;
}

/* 关闭弹窗键 */
.deleye-img {
  transition: transform 0.3s ease;
  cursor: pointer;
}

.deleye-img:hover {
  transform: scale(1.2);
}

.center {
  min-width: 850px;
  border-radius: 15px;
  margin-top: 15px;
  padding: 10px;
  width: 80%;
  height: 980px;
  overflow: auto;
  background-color: rgba(250, 246, 246, 0.504);
  box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25);
  /*阴影 */
}

/* 修改图片框以及默认框的大小 */
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  max-width: 178px;
  min-width: 178px;
  min-height: 178px;
  max-height: 178px;
  text-align: center;
  cursor: pointer;
  border-radius: 15px;
  border: 1px rgb(62, 164, 156, 0.2) solid;
  transition: border 0.3s ease;
}

.add-button {
  margin: 10px;
}

/* 封面图片 */
.FM_img {
  width: 50px;
  height: 50px;
  border-radius: 10px;
}

.bj-img {
  cursor: pointer;
  transition: transform 0.3s ease-in-out;
}

.bj-img:hover {
  transform: scale(1.1);
}

.text-container {
  width: 250px;
  /* 设置容器的最大宽度 */
  white-space: nowrap;
  /* 保持文本在一行内显示，不换行 */
  overflow: hidden;
  /* 隐藏超出容器宽度的部分 */
  text-overflow: ellipsis;
  /* 显示省略号来表示文本被截断 */
  padding: 5px;
  /* 可选，添加内边距 */
}

.xz-bj{
margin-top: 10px;
}
</style>